﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace PaymentHelper.Core.ViewEmbeddedHandler
{
    public class ViewEmbedded
    {
        private AssemblyLoader _loader;

        public ViewEmbedded(AssemblyLoader loader)
        {
            _loader = loader;
        }

        public EmbeddedViewCollection GetEmbeddedViews()
        {
            var assemblies = _loader.GetAssemblies();
            if (assemblies == null || assemblies.Count == 0)
                return null;

            var embeddedViewCollection = new EmbeddedViewCollection();

            foreach (var assembly in assemblies)
            {
                var names = GetNamesOfAssemblyResource(assembly);
                foreach (var name in names)
                {
                    if (!name.ToLowerInvariant().Contains(".views."))
                        continue;
                    embeddedViewCollection.AddView(name, assembly.FullName);
                }
            }

            return embeddedViewCollection;
        }

        private string[] GetNamesOfAssemblyResource(Assembly assembly)
        {
            try
            {
                return assembly.GetManifestResourceNames();
            }
            catch
            {
                return new string[] { };
            }
        }
    }
}
